package com.yexx.starter.security.sms;

import com.yexx.starter.security.basic.BasicLoginFilter;
import com.yexx.starter.security.basic.constant.SecurityConstants;
import com.yexx.utils.CacheUtil;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: 短信验证码认证filter
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/03 14:16
 */
public class SmsCodeAuthenticationFilter extends BasicLoginFilter {

    private CacheUtil cacheUtil;

    protected SmsCodeAuthenticationFilter(String defaultFilterProcessesUrl, String failureUrl, Boolean singleSignOn) {
        super(defaultFilterProcessesUrl, failureUrl, singleSignOn);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String deviceUuid = obtainDeviceUuid(request);
        String phoneNum = obtainMobile(request);
        String smsCode = obtainSmsCode(request);
        String osName = obtainOsName(request);
        String osVersion = obtainOsversion(request);
        if(StringUtils.isEmpty(phoneNum) || StringUtils.isEmpty(smsCode)){
            throw new InternalAuthenticationServiceException("手机号码或者短信验证码错误");
        }
        phoneNum = phoneNum.trim();
        smsCode = smsCode.trim();
        //创建SmsCodeAuthenticationToken(未认证)
        SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(phoneNum, smsCode, deviceUuid, osName, osVersion);
        //设置用户信息
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainSmsCode(HttpServletRequest request) {
        return request.getParameter(SecurityConstants.PARAMETER.LOGIN_SMS_CODE);
    }

    protected String obtainOsName(HttpServletRequest request) {
        String osName = request.getHeader("OS-Name");
        if(StringUtils.isEmpty(osName)){
            osName = request.getParameter("OS-Name");
        }
        return osName;
    }

    protected String obtainOsversion(HttpServletRequest request) {
        String osVersion = request.getHeader("OS-Vsersion");
        if(StringUtils.isEmpty(osVersion)){
            osVersion = request.getParameter("OS-Vsersion");
        }
        return osVersion;
    }

    @Override
    public CacheUtil getCacheUtil() {
        return cacheUtil;
    }

    public void setCacheUtil(CacheUtil cacheUtil) {
        this.cacheUtil = cacheUtil;
    }

}
